package com.hos.punchtheclocksystem.controller;

import com.hos.punchtheclocksystem.pojo.Card;
import com.hos.punchtheclocksystem.pojo.DoctorAccount;
import com.hos.punchtheclocksystem.service.impl.AccountServiceImpl;
import com.hos.punchtheclocksystem.service.impl.InfoServiceImpl;
import com.hos.punchtheclocksystem.service.impl.MyServiceImpl;
import com.hos.punchtheclocksystem.utils.DateUtil;
import com.hos.punchtheclocksystem.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Author: ycc
 * @Date: 2021/9/4 8:41
 */

@Controller
public class MyController {
    @Autowired
    MyServiceImpl service;
    @Autowired
    AccountServiceImpl userService;
    @Autowired
    InfoServiceImpl infoService;
    @Autowired
    RedisTemplate redisTemplate;


    @RequestMapping(value="/test001",method= RequestMethod.POST)
    public void saveJsonUser(@RequestBody Map<String,String> address){
        String city = address.get("city");
        System.out.println(city);
    }

    @RequestMapping(value="/ll")
    public String saveJsonUser0(){
        return "ll";
    }


    @RequestMapping("/allShow")
    public String allShow(){
        return "allShow";
    }






    @RequestMapping({"/login","/toLogin","/"})
    public String Login(){
        return "login";
    }
    @RequestMapping({"/card","/toCard"})
    public String card(HttpServletRequest request,ModelMap modelMap){
        List<Card> cards = new ArrayList<>();
        DoctorAccount loginUser = (DoctorAccount)request.getSession().getAttribute("loginUser");
        Card card = service.oldOrYesterday(loginUser.getDoc_id());
        cards.add(card);
        modelMap.addAttribute("cards", cards);
        return "card";
    }
    @RequestMapping({"/proceedingCard","/toProceedingCard"})
    public String proceedingCard(HttpServletRequest request,ModelMap modelMap){
        List<Card> cards = new ArrayList<>();
        DoctorAccount loginUser = (DoctorAccount)request.getSession().getAttribute("loginUser");
        Card card = service.selectCardToday(loginUser.getDoc_id());
        cards.add(card);
        modelMap.addAttribute("cards", cards);
        return "proceedingCard";
    }



    @RequestMapping({"/historyRecord","/toHistoryRecord"})
    public String historyRecord(HttpServletRequest request,ModelMap modelMap){
        DoctorAccount loginUser = (DoctorAccount)request.getSession().getAttribute("loginUser");
        List<Card> cards = service.selectYourselfProceedingByDocId(loginUser.getDoc_id());
        modelMap.addAttribute("cards",cards);
        return "historyRecord";
    }


    @RequestMapping({"/personal","/toPersonal"})
    public String personal(HttpServletRequest request,ModelMap modelMap){
        DoctorAccount loginUser = (DoctorAccount)request.getSession().getAttribute("loginUser");
        List<DoctorAccount> doctorAccounts = new ArrayList<>();
        doctorAccounts.add(loginUser);
        modelMap.addAttribute("users",doctorAccounts);
        return "personal";
    }


    @RequestMapping({"/change","/toChange"})
    public String change(HttpServletRequest request,
                         @RequestParam("docId") Integer docId,
                         @RequestParam("password0") String password0,
                         @RequestParam("password1") String password1,
                         @RequestParam("password2") String password2,
                         Model model,
                         ModelMap modelMap){
        DoctorAccount loginUser = (DoctorAccount)request.getSession().getAttribute("loginUser");
        List<DoctorAccount> doctorAccounts = new ArrayList<>();

        if (Objects.equals(docId, loginUser.getDoc_id())
                && Objects.equals(Md5Util.encode(password0),loginUser.getPassword())
                && Objects.equals(password1, password2)){
            DoctorAccount doctorAccount1 = userService.selectDoctorByDocId(docId);
            modelMap.clear();
            doctorAccount1.setPassword(Md5Util.encode(password2));
            userService.updateDocById(doctorAccount1);
            request.getSession().removeAttribute("loginUser");
            return "redirect: /login";
        }else {
            doctorAccounts.add(loginUser);
            modelMap.addAttribute("users",doctorAccounts);
            if (!Objects.equals(docId, loginUser.getDoc_id())){
                model.addAttribute("msg","账号错误，可能被非法路径篡改！");
            }
            if (!Objects.equals(Md5Util.encode(password0), loginUser.getPassword())) {
                model.addAttribute("msg", "老密码错误！");
            }
            if (!Objects.equals(password1, password2)) {
                model.addAttribute("msg","新密码两次输入不一致！");
            }
        }
        return "personal";
    }

    @RequestMapping({"/logout","/toLogout"})
    public String logout(HttpServletRequest request){
        request.getSession().removeAttribute("loginUser");
        return "redirect: /login";
    }



    @RequestMapping("/updateCardYcc")
    public String updateCardYcc(HttpServletRequest request,ModelMap modelMap){
        DoctorAccount loginUser = (DoctorAccount)request.getSession().getAttribute("loginUser");
        Card card = service.selectCardToday(loginUser.getDoc_id());
        List<Card> cards = new ArrayList<>();
        cards.add(card);
        modelMap.addAttribute("cards",cards);
        return "card";
    }





    @RequestMapping("/doctor")
    public String login(HttpServletRequest request ,
                        @RequestParam("docId") Integer docId,
                        @RequestParam("password") String password,
                        ModelMap modelMap,
                        Model model){
        //首先，判断医生是否存在，如果存在
        if (infoService.judgeDoctorExistByDocId(docId)) {
            //判断此医生是否存在于 医生打卡账号表
            DoctorAccount user = userService.selectDoctorByDocId(docId);
            //不存在
            if (user == null){
                user = new DoctorAccount();
            }
            user.setDoc_id(docId);
            //如果不存在，
            if (user.getPassword()==null){
                //判断密码是否为 docID后六位
                if (password.equals(String.valueOf(docId).substring(1,7))) {
                    //如果是后六位，就给这个医生生成对应的账号，存到 医生打卡账号表
                    String tem = Md5Util.encode(password);
                    userService.Insert(new DoctorAccount().setDoc_id(docId).setPassword(tem));
                    HttpSession session = request.getSession();
                    user.setPassword(Md5Util.encode(password));
                    session.setAttribute("loginUser", user);
                    List<Card> cards = new ArrayList<>();
                    if (service.selectCardToday(docId) != null) {
                        Card card = service.selectCardToday(docId);
                        cards.add(card);
                        modelMap.addAttribute("cards", cards);
                        return "proceedingCard";
                    } else {
                        List<Card> cardss = new ArrayList<>();
                        DoctorAccount loginUser = (DoctorAccount)request.getSession().getAttribute("loginUser");
                        Card card = service.oldOrYesterday(loginUser.getDoc_id());
                        if (card==null) {
                            card = new Card();
                        }
                        cardss.add(card);
                        modelMap.addAttribute("cards", cardss);
                        return "card";
                    }
                }else {//不是后六位，直接提示错误
                    model.addAttribute("msg", "用户名或密码错误！");
                    return "login";
                }
            }
            if (Md5Util.encode(password).equals(user.getPassword())) {
                HttpSession session = request.getSession();
                redisTemplate.opsForValue().set(String.valueOf(user.getId()),user,30, TimeUnit.MINUTES);
                session.setAttribute("loginUser", user);
                List<Card> cards = new ArrayList<>();
                if (service.selectCardToday(docId) != null) {
                    Card card = service.selectCardToday(docId);
                    cards.add(card);
                    modelMap.addAttribute("cards", cards);
                    return "proceedingCard";
                } else {
                    List<Card> cardss = new ArrayList<>();
                    DoctorAccount loginUser = (DoctorAccount)request.getSession().getAttribute("loginUser");
                    Card card = service.oldOrYesterday(loginUser.getDoc_id());
                    if (card==null){
                        card = new Card();
                    }
                    cardss.add(card);
                    modelMap.addAttribute("cards", cardss);
                    return "card";
                }
            } else {
                model.addAttribute("msg", "用户名或密码错误！");
                return "login";
            }
        }else {
            model.addAttribute("msg", "用户名或密码错误！");
            return "login";
        }
    }

    @RequestMapping("/myDuty")
    public String myDuty(){
        return "patient";
    }
    @RequestMapping("/myCard")
    public String myCard(){
        return "realCard";
    }

    @RequestMapping({"/submit","/toSubmit"})
    public String submit(HttpServletRequest request ,
                         @RequestParam("workerId") Integer workerId,
                         @RequestParam("name")String name,
                         @RequestParam("bodyState")Integer bodyState,
                         @RequestParam("heathCodeState")Integer heathCodeState,
                         @RequestParam("inDangerousPlace")Integer inDangerousPlace,
                         @RequestParam("temperatureToday")Double temperatureToday,
                         @RequestParam("addressOfHome")String addressOfHome,
                         @RequestParam("phoneNumber")Long phoneNumber,
                         @RequestParam("extend")String extend,
                         Model model,
                         ModelMap modelMap) throws InterruptedException {
        DoctorAccount user = (DoctorAccount)request.getSession().getAttribute("loginUser");
        if (Objects.equals(user.getDoc_id(), workerId)){
            Card card=new Card();
            card.setWorkerId(workerId);
            card.setName(name);
            card.setBodyState(bodyState);
            card.setHeathCodeState(heathCodeState);
            card.setInDangerousPlace(inDangerousPlace);
            card.setTemperatureToday(temperatureToday);
            card.setAddressOfHome(addressOfHome);
            card.setPhoneNumber(phoneNumber);
            card.setExtend(extend);
            card.setAssistBit(DateUtil.parseDateToSimple(new Date()));
            if (service.selectCardToday(workerId)!=null) {
                service.deleteByWorkerIdToday(workerId);
            }
            service.punchCard(card);
            Card cardToday = service.selectCardToday(workerId);
            List<Card> cards = new ArrayList<>();
            cards.add(cardToday);
            modelMap.addAttribute("cards",cards);
        }else {
            model.addAttribute("msg","提交失败，提交的工号与登录者不一致，请重新填写提交！");
            List<Card> cardss = new ArrayList<>();
            DoctorAccount loginUser = (DoctorAccount)request.getSession().getAttribute("loginUser");
            Card card = service.oldOrYesterday(loginUser.getDoc_id());
            if (card==null){
                card = new Card();
            }
            cardss.add(card);
            modelMap.addAttribute("cards", cardss);
            return "card";
        }
        return "proceedingCard";
    }

    @RequestMapping({"/judge","toJudge"})
    public String judge(HttpServletRequest request,ModelMap modelMap){
        DoctorAccount doctorAccount = (DoctorAccount)request.getSession().getAttribute("loginUser");
        if (service.selectCardToday(doctorAccount.getDoc_id())!=null)
            return "redirect:/proceedingCard";
        List<Card> cardss = new ArrayList<>();
        DoctorAccount loginUser = (DoctorAccount)request.getSession().getAttribute("loginUser");
        Card card = service.oldOrYesterday(loginUser.getDoc_id());
        if (card==null){
            card = new Card();
        }
        cardss.add(card);
        modelMap.addAttribute("cards", cardss);
        return "card";
    }
}
